package com.xyh.transaction.meilisearch;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.meilisearch.sdk.Client;
import com.meilisearch.sdk.Config;
import com.meilisearch.sdk.Index;
import com.meilisearch.sdk.exceptions.MeilisearchException;
import com.meilisearch.sdk.model.TaskInfo;
import com.xyh.transaction.entity.User;
import org.apache.poi.ss.formula.functions.T;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xiaoyh
 */
public class AddMeilisearchTest {

    public static void main(String[] args) throws MeilisearchException {
        // 如果要根据 director 和 genres 属性过滤结果，则必须首先将它们添加到 filterableAttributes 列表中：此步骤是强制性的，不能在搜索时完成
//        Client client = new Client(new Config("http://localhost:7700", "aSampleMasterKey"));
//        client.index("movies").updateFilterableAttributesSettings(new String[]
//                {
//                        "genres",
//                        "director"
//                });

        addUser();

//        try {
//            // 创建 MeiliSearch 客户端
//            Client client = new Client(new Config("http://localhost:7700", "aSampleMasterKey"));
//            // 服务器meilisearch地址
////            Client client = new Client(new Config("http://124.223.56.87:7700", "aSampleMasterKey"));
//
//            // 读取文件内容
//            String filePath = "C:\\Users\\xiaoyh\\Downloads\\movies (1).json";
//            String moviesJson = readFile(filePath);
//
//            List<Movie> movies = mappingJsonToJava(moviesJson, Movie.class);
//
//            String jsonString = JSONArray.toJSONString(movies);
//
////            System.out.println(moviesJson.substring(0,100));
////            System.out.println("--------------------------------");
////            System.out.println(jsonString.substring(0,100));
//
//            // 设置索引的主键。如果未指定，Meilisearch 将从您添加到索引的第一个文档中猜测您的主键。
//            client.createIndex("movies", "id");
//
//            // 获取索引
//            Index index = client.index("movies");
//
//            // 将文档添加到索引
//            TaskInfo taskInfo = index.addDocuments(jsonString);
//
//            System.out.println("Status: " + taskInfo.getStatus());
//            System.out.println("Task UID: " + taskInfo.getTaskUid());
//            System.out.println("Type: " + taskInfo.getType());
//            System.out.println("Index UID: " + taskInfo.getIndexUid());
//            System.out.println("Enqueued At: " + taskInfo.getEnqueuedAt());
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        catch (MeilisearchException e) {
//            throw new RuntimeException(e);
//        }
    }

    public static <T>List<T> mappingJsonToJava(String json,Class<T> clazz) {
        JSONArray jsonArray = JSONArray.parseArray(json);
        return jsonArray.stream().map( o -> JSONObject.parseObject(o.toString(),clazz))
                .collect(Collectors.toList());
    }

    public static void addUser() throws MeilisearchException {
        new User();
        User zs2 = User.builder().id(1).username("zs2").age(15).email("18111").createTime(LocalDateTime.now()).idCard("21145555").build();
        new User();
        User zs1 = User.builder().id(2).username("zs1").age(16).email("16111").createTime(LocalDateTime.now()).idCard("2555555").build();
        new User();
        User zs3 = User.builder().id(3).username("zs3").age(17).email("15111").createTime(LocalDateTime.now()).idCard("2775555").build();
        new User();
        User zs4 = User.builder().id(4).username("zs4").age(18).email("12111").createTime(LocalDateTime.now()).idCard("2885555").build();
        new User();
        User zs5 = User.builder().id(5).username("zs5").age(19).email("14111").createTime(LocalDateTime.now()).idCard("9995555").build();

        List<User> userList = new ArrayList<>();
        userList.add(zs1);
        userList.add(zs2);
        userList.add(zs3);
        userList.add(zs4);
        userList.add(zs5);

        Client client = new Client(new Config("http://124.223.56.87:7700", "aSampleMasterKey"));

        client.createIndex("user","username");

        Index user = client.index("user");

        TaskInfo taskInfo = user.addDocuments(JSONArray.toJSONString(userList));

        System.out.println("Status: " + taskInfo.getStatus());
        System.out.println("Task UID: " + taskInfo.getTaskUid());
        System.out.println("Type: " + taskInfo.getType());
        System.out.println("Index UID: " + taskInfo.getIndexUid());
        System.out.println("Enqueued At: " + taskInfo.getEnqueuedAt());
    }

    private static String readFile(String filePath) throws IOException {
        StringBuilder content = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
        }
        return content.toString();
    }
}
